package com.yndsoft.jc.supplier.net.util;

import android.content.Context;

import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.supplier.utils.ToastUtil;
import com.yndsoft.jc.supplier.widget.recyclerview.IRecyclerSwipe;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import rx.Subscriber;

public abstract class ProgressSubscriber extends Subscriber<ReturnMsg> implements ProgressCancel {

    private Context context;
    private ProgressDialog handler;
    private IRecyclerSwipe iRecyclerSwipe;

    public ProgressSubscriber(Context context) {
        this(context, null);
    }

    public ProgressSubscriber(Context context, IRecyclerSwipe iRecyclerSwipe) {
        this.context = context;
        this.iRecyclerSwipe = iRecyclerSwipe;
        handler = new ProgressDialog(context, this, true);
    }

    private void showProgressDialog() {
        if (handler != null) {
            handler.obtainMessage(ProgressDialog.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (handler != null) {
            handler.obtainMessage(ProgressDialog.DISMISS_PROGRESS_DIALOG).sendToTarget();
            handler = null;
        }
    }

    @Override
    public void onStart() {
        showProgressDialog();
        super.onStart();
    }

    @Override
    public void onCompleted() {
        if (iRecyclerSwipe != null) {
            iRecyclerSwipe.hideSwipeLoading();
        }
        dismissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        if (iRecyclerSwipe != null) {
            iRecyclerSwipe.hideSwipeLoading();
//            iRecyclerSwipe.showItemFail(iRecyclerSwipe.getName() + " 列表数据获取失败！");
        }
        if (e instanceof SocketTimeoutException) {
            ToastUtil.show(context, "网络中断，请检查您的网络状态！");
        } else if (e instanceof ConnectException) {
            ToastUtil.show(context, "网络中断，请检查您的网络状态！");
        } else {
            ToastUtil.show(context, "error:" + e.getMessage());
        }
        dismissProgressDialog();
    }

    @Override
    public void onNext(ReturnMsg returnMsg) {
        if (returnMsg != null) {
            next(returnMsg);
        }
        if (iRecyclerSwipe != null) {
            iRecyclerSwipe.hideSwipeLoading();
        }
    }

    @Override
    public void onCancel() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }

    public abstract void next(ReturnMsg returnMsg);
}
